
package models.aaa;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.Id;

import models.Store;
import play.db.jpa.JPA;

import com.google.common.base.Objects;

/**
 * 
 * @author laurent@opprecht.info
 */
@Entity
public class Tag {

    public static class Finder {

        public Tag byId(final String tag) {
            return JPA.em().find(Tag.class, tag);
        }
    }

    @SuppressWarnings("unused")
    private static final long serialVersionUID = 7206841314655210890L;

    public static Finder      find             = new Finder();

    public static Tag get(final String tag) {
        if (tag == null) {
            return null;
        }
        if (Objects.equal(tag, "")) {
            return null;
        }
        Tag result = find.byId(tag);
        if (result != null) {
            return result;
        }
        result = new Tag(tag);
        Store.save(result);
        return result;
    }

    public static boolean has(final String tag) {
        Tag result = find.byId(tag);
        return result != null;
    }

    public static boolean has(final Tag tag) {
        Tag result = find.byId(tag.toString());
        return result != null;
    }

    public static List<Tag> get(final List<String> names) {
        List<Tag> result = new ArrayList<Tag>();
        for (String name : names) {
            result.add(get(name));
        }
        return result;
    }

    @Id
    private String value = null;

    protected Tag() {
        ;
    }

    protected Tag(final String value) {
        setValue(value);
    }

    public String getValue() {
        return value;
    }

    protected void setValue(String value) {
        if (value == null) {
            value = "";
        }
        value = value.trim();
        this.value = value;
    }

    @Override
    public String toString() {
        if (getValue() == null) {
            return "";
        }
        return getValue().toString();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((value == null) ? 0 : value.hashCode());
        return result;
    }

    @Override
    public boolean equals(final Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        Tag other = (Tag) obj;
        if (value == null) {
            if (other.value != null) {
                return false;
            }
        } else if (!value.equals(other.value)) {
            return false;
        }
        return true;
    }
}
